﻿using Ninject;
using SelfManagement.Web.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SelfManagement.Web.Models.ViewModels.AccountModels;
using SelfManagement.Mvc.Result;
using SelfManagement.Database.POCO;
using SelfManagement.Account.Manager;
using SelfManagement.Web.Models.Session;
using SelfManagement.Utility.Extensions;
using SelfManagement.IServices;
using SelfManagement.Mvc.Helper;

namespace SelfManagement.Web.Controllers
{
    public class AccountController : CommonBaseController
    {
        [Inject]
        public UserManager UserManager { get; set; }
        [Inject]
        public IUserService UserService { get; set; }

        // GET: Account
        [HttpGet]
        public ActionResult Login(string returnUrl)
        {
            SetPageTitle(title: "登录");
            LoginRegisterViewModel viewModel = new LoginRegisterViewModel();
            viewModel.LoginModel.ReturnUrl = returnUrl;
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult Login(LoginModel postModel)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                if (ModelState.IsValid)
                {
                    UserStatus userStatus;
                    bool valid = UserManager.ValidateUser(postModel.UserName, postModel.Password, out userStatus);

                    if (!valid)
                    {
                        ModelState.AddModelError("PasswordError", "账户或密码错误");
                        result.AddModelValidErrorMessage(ModelState);
                    }
                    else if (userStatus == UserStatus.Locked)
                    {
                        ModelState.AddModelError("Locked", "此账号被锁定，请稍后再试，或与客服联系。");
                        result.AddModelValidErrorMessage(ModelState);
                    }
                    else
                    {
                        var user = UserManager.Get(postModel.UserName);

                        if (userStatus == UserStatus.Unactive)
                        {
                            //未激活账号，第一次访问自动激活
                            user.Status = UserStatus.Normal;
                            UserManager.Update(user);
                            result.AddSuccessMessage("账号激活成功！~~");
                        }
                        else
                        {
                            result.AddSuccessMessage("登录成功！");
                        }

                        var userSession = new UserSession(user);
                        UserService.InitUserData(user); // 初始化用户数据
                        //登录成功
                        UserSignIn(userSession, postModel.RememberMe);
                        result.Success = true;
                        result.RedirectUrl = postModel.ReturnUrl.IfNullOrWhiteSpace(Url.Action("Index", "Home"));

                    }
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });

            return Json(result);
        }

        public ActionResult Logout()
        {
            UserSignOut();
            if (Request.UrlReferrer != null)
            {
                return Redirect(Request.UrlReferrer.AbsolutePath);
            }
            return RedirectToAction("Index", "Home");
        }
        
        [HttpPost]
        public ActionResult Register(RegisterModel postModel)
        {
            var result = new JsonResultData();

            result.RunWithTry(item =>
            {
                if (ModelState.IsValid)
                {
                    User user = new Database.POCO.User
                    {
                        UserName = postModel.UserName,
                        Password = postModel.Password,
                        Phone = postModel.Phone,
                        Email = postModel.Email,
                        TrueName = postModel.TrueName,
                        Status = UserStatus.Normal,
                    };
                    
                    UserManager.Add(user);
                    UserService.InitUserData(user); // 初始化用户数据

                    //注册成功
                    UserSignIn(new UserSession(user), true);
                    result.Success = true;
                    result.AddMessage("注册成功！");
                    result.RedirectUrl = Url.Action("Index", "Home");
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            }, Logger);

            return Json(result);
        }

        #region 个人资料
        /// <summary>
        /// 个人资料
        /// </summary>
        /// <returns></returns>
        [UserAuthorize]
        public ActionResult MyProfile()
        {
            User user = UserManager.Get(UserSession.UserEntity.UserName);
            MyProfileViewModel viewModel = new MyProfileViewModel()
            {
                UserFace = user.UserFace,
                TrueName = user.TrueName,
                Sex = user.Sex,
                Identity = user.Identity,
                PersonalInfo = user.PersonalInfo,
                SexOptions = SelectListItemsHelper.FromEnum(typeof(Sex))
            };

            SetPageTitle("账户设置");
            return View(viewModel);
        }

        [HttpPost]
        [UserAuthorize]
        public ActionResult MyProfile(MyProfileViewModel post)
        {
            JsonResultData result = new JsonResultData();
            result.RunWithTry(data =>
            {
                if (ModelState.IsValid)
                {
                    User user = UserManager.Get(UserSession.UserEntity.UserName);
                    user.TrueName = post.TrueName;
                    if (post.NewPassword.IsNotNullAndNotWhiteSpace())
                    {
                        if (post.Password.IsNullOrWhiteSpace())
                        {
                            result.AddMessage("请输入原密码");
                            return;
                        }
                        if(!UserManager.SetIfChangePassword(user, post.Password, post.NewPassword))
                        {
                            result.AddMessage("密码错误");
                            return;
                        }
                    }
                    var faceUrl = SaveUserFile("Face", user.Id, SiteConstants.USER_FACE_SAVE_PATH);
                    user.UserFace = faceUrl ?? user.UserFace;
                    user.Sex = post.Sex;
                    user.PersonalInfo = post.PersonalInfo;
                    user.Identity = post.Identity;
                    user.SetUpdateInfo(user.UserName);
                    UserManager.Update(user);
                    UserSession = new UserSession(user);
                    result.Success = true;
                    result.ReloadPage = true;
                    result.AddMessage("设置成功！");
                }
                else
                {
                    result.AddModelValidErrorMessage(ModelState);
                }
            });
            return Json(result);
        }
        #endregion
    }
}